/**
 * Responsive Hot Topic Panel Component
 * 响应式热点话题面板组件 - 桌面端侧边栏，移动端抽屉
 */
import React, { useState, useEffect } from 'react';
import { Card, Tabs, List, Button, Tag, Space, Spin, message, Badge, Drawer } from 'antd';
import {
  FireOutlined,
  RiseOutlined,
  CommentOutlined,
  EyeOutlined,
  CloseOutlined
} from '@ant-design/icons';
import { useBreakpoint } from '../../../hooks/useBreakpoint';
import { Show, Hide } from '../../Responsive/ResponsiveExports';
import { hotRadarService } from '../../../services/hotRadar.service';
import { generationService } from '../../../services/generation.service';
import { useConversationStore } from '../../../stores/conversation.store';
import HotTopicCard from './HotTopicCard';
import CommentView from './CommentView';
import './responsive-style.css';

interface HotTopic {
  id: string;
  title: string;
  excerpt: string;
  platform: string;
  rank: number;
  hot_value: number;
  url: string;
  comments?: Comment[];
  created_at: string;
}

interface Comment {
  content: string;
  author: string;
  likes: number;
  sentiment?: string;
}

interface ResponsiveHotTopicPanelProps {
  visible?: boolean;
  onClose?: () => void;
  onTopicSelect?: (topic: HotTopic) => void;
}

const PLATFORMS = [
  { key: 'weibo', label: '微博', icon: '🔥' },
  { key: 'zhihu', label: '知乎', icon: '💡' },
  { key: 'toutiao', label: '头条', icon: '📰' },
  { key: 'douyin', label: '抖音', icon: '🎵' },
  { key: 'xiaohongshu', label: '小红书', icon: '📖' },
];

const ResponsiveHotTopicPanel: React.FC<ResponsiveHotTopicPanelProps> = ({
  visible = true,
  onClose,
  onTopicSelect
}) => {
  const breakpoint = useBreakpoint();
  const isMobile = breakpoint === 'mobile';

  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState('weibo');
  const [hotTopics, setHotTopics] = useState<HotTopic[]>([]);
  const [selectedTopic, setSelectedTopic] = useState<HotTopic | null>(null);
  const [showComments, setShowComments] = useState(false);

  const { setHotTopicContext, startNewConversation } = useConversationStore();

  // 获取热点数据
  const fetchHotTopics = async (platform: string) => {
    setLoading(true);
    try {
      const data = await hotRadarService.getLatestHotData(platform);
      setHotTopics(data.items || []);
    } catch (error) {
      console.error('Failed to fetch hot topics:', error);
      message.error('获取热点数据失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (visible) {
      fetchHotTopics(activeTab);
    }
  }, [activeTab, visible]);

  // 基于热点开始创作
  const handleStartWriting = async (topic: HotTopic) => {
    try {
      setLoading(true);

      // 生成智能提示词
      const promptData = await generationService.generateHotTopicPrompt({
        title: topic.title,
        excerpt: topic.excerpt,
        platform: topic.platform
      });

      // 设置热点上下文
      setHotTopicContext({
        platform: topic.platform,
        topicId: topic.id,
        title: topic.title,
        excerpt: topic.excerpt,
        comments: topic.comments || [],
        perspectives: [],
        generatedPrompt: promptData.prompt
      });

      // 开始新对话
      await startNewConversation(promptData.prompt);

      message.success('已基于热点生成创作提示');

      // 通知父组件
      onTopicSelect?.(topic);

      // 移动端选择后关闭抽屉
      if (isMobile && onClose) {
        onClose();
      }
    } catch (error) {
      console.error('Failed to start writing:', error);
      message.error('生成创作提示失败');
    } finally {
      setLoading(false);
    }
  };

  // 查看评论
  const handleViewComments = (topic: HotTopic) => {
    setSelectedTopic(topic);
    setShowComments(true);
  };

  // 渲染热点列表
  const renderHotTopicList = () => (
    <Spin spinning={loading}>
      <List
        dataSource={hotTopics}
        renderItem={(topic) => (
          <HotTopicCard
            topic={topic}
            onStartWriting={() => handleStartWriting(topic)}
            onViewComments={() => handleViewComments(topic)}
            isMobile={isMobile}
          />
        )}
        locale={{ emptyText: '暂无热点数据' }}
        className={isMobile ? 'mobile-hot-topic-list' : 'hot-topic-list'}
      />
    </Spin>
  );

  // 桌面端内容
  const desktopContent = (
    <Card
      title={
        <Space>
          <FireOutlined />
          <span>热点创作</span>
        </Space>
      }
      className="hot-topic-panel-card"
    >
      <Tabs
        activeKey={activeTab}
        onChange={setActiveTab}
        items={PLATFORMS.map(platform => ({
          key: platform.key,
          label: (
            <span>
              {platform.icon} {platform.label}
            </span>
          ),
          children: renderHotTopicList()
        }))}
      />

      {/* 评论查看器 */}
      {selectedTopic && (
        <Drawer
          title="评论详情"
          placement="right"
          width={400}
          open={showComments}
          onClose={() => setShowComments(false)}
        >
          <CommentView
            comments={selectedTopic.comments || []}
            topicTitle={selectedTopic.title}
          />
        </Drawer>
      )}
    </Card>
  );

  // 移动端抽屉内容
  const mobileContent = (
    <Drawer
      title={
        <div className="mobile-drawer-header">
          <Space>
            <FireOutlined />
            <span className="text-mobile-base font-bold">热点创作</span>
          </Space>
        </div>
      }
      placement="right"
      width="85%"
      open={visible}
      onClose={onClose}
      className="hot-topic-mobile-drawer"
      closeIcon={<CloseOutlined className="h-touch w-touch" />}
    >
      <Tabs
        activeKey={activeTab}
        onChange={setActiveTab}
        className="mobile-tabs"
        items={PLATFORMS.map(platform => ({
          key: platform.key,
          label: (
            <span className="text-mobile-sm">
              {platform.icon} {platform.label}
            </span>
          ),
          children: renderHotTopicList()
        }))}
      />

      {/* 移动端评论抽屉 */}
      {selectedTopic && (
        <Drawer
          title="评论详情"
          placement="bottom"
          height="70%"
          open={showComments}
          onClose={() => setShowComments(false)}
          className="comments-mobile-drawer"
        >
          <CommentView
            comments={selectedTopic.comments || []}
            topicTitle={selectedTopic.title}
          />
        </Drawer>
      )}
    </Drawer>
  );

  return (
    <>
      <Hide breakpoint="mobile">
        {desktopContent}
      </Hide>

      <Show breakpoint="mobile">
        {mobileContent}
      </Show>
    </>
  );
};

export default ResponsiveHotTopicPanel;
